//
//  STSportingSpeaker.m
//  STBest
//
//  Created by apple on 2017/8/30.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "STSportingSpeaker.h"
#import "STSportingManager.h"
#import <AVFoundation/AVFoundation.h>

@interface STSportingSpeaker ()

//@property(strong, nonatomic) AVSpeechSynthesizer   *speechSynthesizer;

// 全局声音播放器
@property(strong, nonatomic)AVQueuePlayer   *player;

@property (strong, nonatomic)   NSDictionary        *voiceDict;

@end
@implementation STSportingSpeaker{
    double _beginDistance;
}


//#pragma mark - 属性重写 -
//- (AVSpeechSynthesizer *)speechSynthesizer {
//    if(_speechSynthesizer == nil) {
//        _speechSynthesizer = [AVSpeechSynthesizer new];
//    }
//    return _speechSynthesizer;
//}

+ (STSportingSpeaker *)sharedInstance{
    static dispatch_once_t onceToken;
    static STSportingSpeaker *__Instance__;

    dispatch_once(&onceToken, ^{
        
        __Instance__ = [STSportingSpeaker new];
    });
    
    return __Instance__;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _canSpeak = NO;
        _player = nil;
        self.speakDistanceInterval = 1;
        _beginDistance = _speakDistanceInterval;
        [self setupNotifications];
        
    }
    return self;
}

// 加载声音配置文件
- (NSDictionary *)voiceDict{
    if(_voiceDict == nil){
        
        NSURL *dataurl = [[NSBundle mainBundle] URLForResource:@"voice.bundle/voice" withExtension:@"json"];
        
        NSError *error = nil;
        
        _voiceDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:dataurl] options:NSJSONReadingAllowFragments error:&error];
        
        if(error){
            
            //NSLog(@"error:%@",error);
        }
    }
    
    return _voiceDict;
}

#pragma mark - 私有方法 -
// 通过字符串的key生成声音文件路径
- (NSString *)voicePathWithKey:(NSString *)key {
    return [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"voice.bundle/%@",self.voiceDict[key]] ofType:@""];
}


// 线段被添加时回调
- (void)sporingTrackingLineDidBeGeneratedNotification:(NSNotification *)notification{
    
    // 播报
    // @"你已经 %@%@ 公里 用时%@ 平均速度%@ 公里每小时 太棒了"
    // 获取当前使用的距离
    double distance = _SportingMgr.sportingsportingTracking.distance;
    
    // 处理播报逻辑
    if(distance > _beginDistance){
        
        // 获取跑步类型字符串
        NSString *sportTypeText;
        switch (_SportingMgr.sportingsportingTracking.type) {
            case STSportingTrackingTypeWalk:
                sportTypeText = @"走路";
                break;
            case STSportingTrackingTypeRun:
                sportTypeText = @"跑步";
                break;
            case STSportingTrackingTypeRide:
                sportTypeText = @"骑行";
                break;
                
            default:
                break;
        }

        NSString *distanceText = [self speakTextWithNumber:distance];
        NSString *timeText = [self speakTextWithTimeInterval:_SportingMgr.sportingsportingTracking.duration];
         NSString *avgSpeedText = [self speakTextWithNumber:_SportingMgr.sportingsportingTracking.avgSpeed];
        
        NSString *text = [NSString stringWithFormat:@"你已经 %@ %@ 公里 用时 %@ 平均速度 %@ 公里每小时 太棒了",sportTypeText,distanceText,timeText,avgSpeedText];

        [self speakText:text];
        
        _beginDistance += self.speakDistanceInterval;
        
        
    }
    
}


// 通过时间来返回播报的字符串
- (NSString *)speakTextWithTimeInterval:(NSTimeInterval)timeInterval
{
    // 时长
    // xx 小时 xx 分钟 xx 秒
    NSInteger hour   = (NSInteger)(timeInterval /3600);
    NSInteger minute = (NSInteger)((timeInterval - hour * 60 * 60 ) / 60);
    NSInteger second = ((NSInteger)timeInterval % 60);
    
    NSString *hourText = [self speakTextWithNumber:hour];
    NSString *minuteText = [self speakTextWithNumber:minute];
    NSString *secondText = [self speakTextWithNumber:second];
    
    return [NSString stringWithFormat:@"%@ 小时 %@ 分钟 %@ 秒",hourText,minuteText,secondText];
}

#pragma mark - 通知管理 -
- (void)setupNotifications {
    
    // 监视运动状态发生变化时候通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sportingEventTriggerNotification:) name:STSportingEventTriggerNotification object:_SportingMgr];
    
    // 监视线段被添加时回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sporingTrackingLineDidBeGeneratedNotification:) name:STSporingTrackingLineDidBeGeneratedNotification object:_SportingMgr];
}

- (void)sportingEventTriggerNotification:(NSNotification *)notification{
    // 获取状态
    STSportingEvent event = [notification.userInfo[kSportEvent] integerValue];
    
    
    /*
     STSportingEventBegin,   // 运动开始
     STSportingEventPause,   // 运动暂停
     STSportingEventResume,  // 运动恢复
     STSportingEventEnd,     // 运动结束
     STSportingEventCancel,  // 运动取消
     STSportingEventGPSDisenable,    // GPS信号丢失事件
     STSportingEventGPSEnable        // GPS信号可用
     */
    switch (event) {
        case STSportingEventBegin:
            [self speakText:@"运动已开始"];
            
            switch (_SportingMgr.sportingsportingTracking.type) {
                case STSportingTrackingTypeRun:
                    [self speakText:@"开始跑步"];
                    break;
                case STSportingTrackingTypeWalk:
                    [self speakText:@"开始走路"];
                    break;
                case STSportingTrackingTypeRide:
                    [self speakText:@"开始骑行"];
                    break;
                    
                default:
                    break;
            }
            break;
        case STSportingEventPause:
            [self speakText:@"运动已暂停"];
            break;
        case STSportingEventResume:
            [self speakText:@"运动已恢复"];
            break;
        case STSportingEventEnd:
            [self speakText:@"放松一下吧"];
            break;
        case STSportingEventCancel:
            [self speakText:@"放松一下吧"];
            break;
        case STSportingEventGPSDisenable:
            [self speakText:@"GPS已丢失"];
            break;
        case STSportingEventGPSEnable:
            [self speakText:@"GPS已恢复"];
            break;
            
        default:
            break;
    }
}


#pragma mark - 语音播报 -
// 语音播报内容
- (void)speakText:(NSString *)text {
    
    if(! self.canSpeak) return;
    NSLog(@"speakText:%@",text);
    
    /*
    // 采用系统语音播报功能
    // 1. 语音合成器
    AVSpeechSynthesizer *speechSynthesizer = self.speechSynthesizer;
    
    // 2. 创建语音片段 -> 要说的话
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    
    //设置的语音
    // Language 使用哪国语言阅读
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh_CN"];
    // ID 就是人的id
//    utterance.voice = [AVSpeechSynthesisVoice voiceWithIdentifier:@""];
    
    // 3. 说话
    [speechSynthesizer speakUtterance:utterance];
    */
    
    
    // 分割播报
    NSArray *textArray = [text componentsSeparatedByString:@" "];
    
    NSMutableArray *items = [NSMutableArray array];
    
    // 循环播放列表
    for (NSString *text in textArray) {
        
        //通过 text 获取声音文件路径
        NSString *audipPath = [self voicePathWithKey:text];
        
        // 播放声音文件
        if(![[NSFileManager defaultManager] fileExistsAtPath:audipPath]) {
            return ;
        }
        
        NSURL *audioURL = [NSURL fileURLWithPath:audipPath];
        
        
        //需要创建一个播放项
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:audioURL];
        
                [items addObject:item];
        }
    
     //创建播放列表
    self.player = [[AVQueuePlayer alloc] initWithItems:items];
    
    //播放
    [self.player play];
}
// 把数字转换成可以播报的字符串
- (NSString *)speakTextWithNumber:(double)number{
    
    // 十 1 . 4 5
    // 2 百 0 十 4 => 2 百 0 4 . 4 5
    // 2 千 0 百 0 十 4 => 2 千 0 4 . 4 5

    
    // 1.25   =>   1 . 2 5
    
    // 11.87  => 十 1 . 8 7
    
    // 111.87 =>  1 百 1 十 1 . 8 7
    
    // 最终返回的字符串
    NSMutableString *speakText = [NSMutableString string];
    
    // 把数字转成字符串
    NSString *numberString;
    if((number - (NSInteger)number) == 0) {
        numberString = [NSString stringWithFormat:@"%zd",(NSInteger)number];
    } else {
        numberString = [NSString stringWithFormat:@"%.2f",number];
    }
    
    // 把数字切割成 2部分 整数部分和小数部分
    NSRange dotRange = [numberString rangeOfString:@"."];
    
   
    
    // 处理整数部分
    NSString *integerString;
    if(dotRange.location != NSNotFound){
        integerString = [numberString substringToIndex:dotRange.location];
    }else{
        integerString = numberString;
    }
    
    
    
    NSArray *units = @[@"十",@"百",@"千",@"万"];
     NSInteger unitIndex = 0;
    
    //循环整数部分的字符
    for (NSInteger i = integerString.length - 1; i >= 0 ; i--) {
        
       unichar ch = [integerString characterAtIndex:i];
        
        //判定是否前面还有字符
        if(i - 1 >= 0){
            
            //前面如果有字符
             unichar beforeCh = [integerString characterAtIndex:i - 1];
            
            if(beforeCh != '0'){
                
                if(ch == '0'){
                    NSInteger tmp = [[integerString substringFromIndex:i] integerValue];
                    
                    if(tmp != 0){
                        
                        // 插入字符
                        [speakText insertString:[NSString stringWithFormat:@" %c",ch] atIndex:0];
                        // 插入单位
                        [speakText insertString:[NSString stringWithFormat:@" %@",units[unitIndex]] atIndex:0];
                    }else{
                        
                        // 插入单位
                        [speakText insertString:[NSString stringWithFormat:@" %@",units[unitIndex]] atIndex:0];
                    }
                    
                }else{
                    
                    // 插入字符
                    [speakText insertString:[NSString stringWithFormat:@" %c",ch] atIndex:0];
                    // 插入单位
                    [speakText insertString:[NSString stringWithFormat:@" %@",units[unitIndex]] atIndex:0];
                }
                
            }else if(beforeCh == '0' && ch != '0'){
                
                // 插入字符
                [speakText insertString:[NSString stringWithFormat:@" %c",ch] atIndex:0];
            }
            
        }else{
            
            // 插入字符
            [speakText insertString:[NSString stringWithFormat:@"%c",ch] atIndex:0];
        }
        
        unitIndex ++;
    }
    // 处理十情况
    if(integerString.length == 2 && [integerString characterAtIndex:0] == '1') {
        [speakText deleteCharactersInRange:NSMakeRange(0, 2)];
    }
    
    // 如果找到小数点
    if(dotRange.location != NSNotFound){
        [speakText appendFormat:@" "];
        //获取小数部分字符串
        NSString *decimalString = [numberString substringFromIndex:dotRange.location];
        
        for (NSInteger i = 0; i< decimalString.length; i++) {
            
            [speakText appendFormat:@"%c ",[decimalString characterAtIndex:i]];
        }
        
        [speakText deleteCharactersInRange:NSMakeRange(speakText.length -1, 1)];
        
    }
    
    NSLog(@"decimalString =%@",speakText);
    
    
    return speakText;
}


- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc{
    [self teardownNotifications];
}
@end
